package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.basic.vo.UserLoginResponseVo;
import com.corpgovernment.api.organization.enums.LoginTypeEnum;
import com.corpgovernment.api.organization.model.user.login.MbUserLoginVo;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.factory.LoginSourceServiceFactory;
import com.ctrip.corp.obt.auth.client.handler.token.JwtTokenHandler;
import com.ctrip.corp.obt.auth.core.token.OAuth2AccessToken;
import com.ctrip.corp.obt.generic.core.context.TenantContext;
import com.ctrip.corp.obt.generic.utils.ExceptionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;

/**
 * @author jhxue
 * @create 2022-02-18-14:21
 */
@Service
@Slf4j
public class PasswordLoginService extends AbstractLoginService {

    @Autowired
    private JwtTokenHandler jwtTokenHandler;
    @Autowired
    private LoginSourceServiceFactory loginSourceServiceFactory;

    @Override
    public UserLoginResponseVo login(MbUserLoginVo request) {
        String clientId = TenantContext.getClientId();
        if (clientId == null) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "clientId");
        }
        if (StringUtils.isBlank(request.getAccountName())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "cccountName");
        }
        if (StringUtils.isBlank(request.getPwd())) {
            throw new CorpBusinessException(OrganizationResponseCodeEnum.PARAMS_IS_NULL, "pwd");
        }
        String accountName = request.getAccountName();
        OAuth2AccessToken oAuth2AccessToken = ExceptionUtils.catchThrow(
                () -> jwtTokenHandler.createAccessTokenByPwd(
                        clientId,
                        request.getAccountName(),
                        request.getPwd(),
                        false,
                        Collections.singletonMap("source", request.getSource())),
                exception -> new CorpBusinessException(OrganizationResponseCodeEnum.CUSTOM_CONTENT, exception.getMessage()));
        log.info("create access token info:{} by pwd", JsonUtils.toJsonString(oAuth2AccessToken));
        Map<String, Object> userInfoByAccessToken = ExceptionUtils.catchThrow(
                () -> jwtTokenHandler.getUserInfoByAccessToken(clientId, oAuth2AccessToken.getValue()),
                exception -> new CorpBusinessException(OrganizationResponseCodeEnum.CUSTOM_CONTENT, exception.getMessage()));
        BaseUserInfo userInfo = JsonUtils.convert(userInfoByAccessToken, BaseUserInfo.class);
        userInfo.setToken((String) userInfoByAccessToken.get("id"));
        UserLoginResponseVo response = new UserLoginResponseVo();
        response.setToken(oAuth2AccessToken.getValue())
                .setUserName(userInfo.getUserName())
                .setUid(userInfo.getUid())
                .setAccountName(accountName)
                .setBgUser(userInfo.getBgUser())
                .setSource(userInfo.getSource())
                .setCid((String) userInfoByAccessToken.get("cid"))
//				.setPhoneNum(mbUserLogin.getPhoneNum())
//				.setCountryCode(mbUserLogin.getCountryCode())
                .setShowManage(false)
                .setRefreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .setExpiration(oAuth2AccessToken.getExpiration());
        return loginSourceServiceFactory.getLoginSourceService(request.getSource()).process(userInfo, response, LoginTypeEnum.PASSWORD);
    }

    @Override
    public String getLoginType() {
        return LoginTypeEnum.PASSWORD.toString();
    }

}
